package utils

import (
	"database/sql"
	"log"
	"net"
	"os"
	"probeping/src/model"
	"probeping/src/store"

	"github.com/pelletier/go-toml"
)

const (
	ConfigFileName = "config.toml"
)

func ReadConfig(filename string) model.Config {
	config := model.Config{}
	// 读取TOML文件
	file, err := os.ReadFile(filename)
	if err != nil {
		log.Fatal("Config Not Found!")
	} else {
		err := toml.Unmarshal(file, &config)
		if err != nil {
			log.Fatal(err)
		}
	}

	return config
}

func ParseConfig(ver string) {
	store.Root = GetRoot()
	cfile := ConfigFileName
	if !IsExist(store.Root + string(os.PathSeparator) + "conf" + string(os.PathSeparator) + cfile) {
		log.Fatalln("[Fault]config file:", store.Root+string(os.PathSeparator)+"conf"+string(os.PathSeparator)+cfile, " not existent.")
	}
	store.Cfg = ReadConfig(store.Root + string(os.PathSeparator) + "conf" + string(os.PathSeparator) + cfile)
	store.Cfg.Ver = ver
	if store.Cfg.Port == 0 {
		port, err := GetAvailablePort()
		if err != nil {
			log.Fatalln("[Fault]config file:", "can not get a available port.")
		}
		store.Cfg.Port = port
	}
	if store.Cfg.Name == "" {
		store.Cfg.Name, _ = os.Hostname()
	}
	if store.Cfg.Addr == "" {
		ips, _ := net.LookupIP(store.Cfg.Name)
		for _, ip := range ips {
			if ip.To4() != nil {
				store.Cfg.Addr = ip.To4().String()
			}
		}
	}
	if store.Cfg.ArchiveDay == 0 {
		store.Cfg.ArchiveDay = 7
	}

	var Db *sql.DB
	var err error
	var dbPath = store.Root + string(os.PathSeparator) + "db" + string(os.PathSeparator)
	if _, err := os.Stat(dbPath); os.IsNotExist(err) {
		err := os.Mkdir(dbPath, os.ModePerm)
		if err != nil {
			log.Fatal("Create Db Path Error:", err)
		}
	}

	if !IsExist(dbPath + "database.db") {
		dst, err := os.OpenFile(dbPath+"database.db", os.O_WRONLY|os.O_CREATE, 0644)
		if err != nil {
			log.Fatalln("[Fault]db-base file create error.")
		}
		defer dst.Close()
		Db, err = sql.Open("sqlite", dbPath+"database.db")
		if err != nil {
			log.Fatalln("[Fault]db open fail .", err)
		}

		sql := `CREATE TABLE pinglog (
					logtime  VARCHAR (16),
					target   VARCHAR (15),
					maxdelay FLOAT,
					mindelay FLOAT,
					avgdelay FLOAT,
					sendpk   INT,
					revcpk   INT,
					losspk   INT
				);
				CREATE UNIQUE INDEX pinglogindex ON pinglog (logtime, target);`
		store.DLock.Lock()
		_, err = Db.Exec(sql)
		if err != nil {
			log.Fatalln("[func:CreateDb] Sql Error ", err)
		}
		store.DLock.Unlock()
	} else {
		Db, err = sql.Open("sqlite", dbPath+"database.db")
		if err != nil {
			log.Fatalln("[Fault]db open fail .", err)
		}
	}

	store.Db = Db

	log.Printf("%+v\n", store.Cfg)
}
